<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>前端实现限时秒杀</title>
  <style>
    *,
    *::after,
    *::before {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      min-height: 100vh;
    }

    :root:focus-within {
      scroll-behavior: smooth;
    }

    body {
      min-height: inherit;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    #countDown {
      color: #333;
      font-size: 30px;
      font-weight: bold;
      user-select: none;
    }

    #countDown>span {
      color: deeppink;
      margin-left: 10px;
    }
  </style>
</head>

<body>
  <div id="countDown"></div>
</body>
<script>
  "use strict"; {
    let t = Date.now()
    let serverTime = Number(t)
    let s = 60 * 60 * 30
    let m = (s / 60)
    let h = (m / 60)
    // String(Math.floor(num)).padStart(2, "0")
    console.log("h ==", s, m, h)

    let targetTime = Number(new Date(2024, 9, 28, 23, 10, 8));
    console.log("targetTime", targetTime)
    function countDown(serverTime) {
      // 本地时间同服务器时间差值
      const diffTime = serverTime - Date.now()
      let startTime = Date.now()

      let cb = () => {
        let id = requestAnimationFrame(cb)
        if (Date.now() - startTime < 100) return;
        startTime += 100
        // 计算出当前时间
        let curTime = Date.now() + diffTime
        let duration = targetTime - curTime
        // console.log("duration ==", duration)

        if (duration <= 0) {
          // 秒杀时间到了
          cancelAnimationFrame(id)
          duration = 0
          // 更新按钮事件
        }
        render(duration)
      }
      cb()
    }
    countDown(serverTime)

    function format(num) {
      return String(Math.floor(num)).padStart(2, "0")
    }

    function render(duration) {
      let s = duration / 1000
      let m = s / 60
      let h = m / 60


      s = format(s % 60)
      m = format(m % 60)
      h = format(h)
      // 获取毫秒
      let milli = format((duration % 1000) / 100)

      let html = `限时秒杀:<span>${h}:${m}:${s}:${milli}</span>`
      document.getElementById("countDown").innerHTML = html
    }
  };
</script>

</html>